import DropFactory from './DropFactory.js'
import lodash from 'lodash'

async function preview({ source='副本', layer=1, times=1 }){
  const results = []
  for (let i=0;i<times;i++){
    const r = await DropFactory.drop(source, layer)
    results.push(r)
  }
  // 汇总
  const all = lodash.flatten(results.map(r=>r.掉落))
  const byCat = lodash.groupBy(all, x=>x.类别)
  const summary = {}
  for (const k of Object.keys(byCat)){
    summary[k] = byCat[k].length
  }
  // Top5 按名称+部位/套装
  const keyOf = (x)=>{
    const parts = [x.类别, x.套装名称, x.元素, x.名称, x.部位, x.星级, x.稀有度]
    return parts.filter(Boolean).join('-')
  }
  const freq = {}
  for (const it of all){
    const k = keyOf(it)
    freq[k] = (freq[k]||0)+1
  }
  const top = Object.entries(freq).sort((a,b)=>b[1]-a[1]).slice(0,5)
  // 文本输出
  const lines = []
  lines.push(`来源: ${source} 层级: ${layer} 次数: ${times}`)
  lines.push(`类别汇总: ${Object.entries(summary).map(([k,v])=>`${k}:${v}`).join(' | ')}`)
  lines.push(`高频掉落 Top5:`)
  for (const [name,count] of top){
    lines.push(`- ${name} ×${count}`)
  }
  // 本次详细（最近一次）
  const last = results[results.length-1]
  const detail = lodash.groupBy(last.掉落, x=>x.类别)
  lines.push(`最近一次详细:`)
  for (const cat of Object.keys(detail)){
    const arr = detail[cat]
    lines.push(`【${cat}】数量:${arr.length}`)
    for (const it of arr){
      const part = it.部位 ? `(${it.部位})` : ''
      const suit = it.套装名称 ? `[${it.套装名称}]` : ''
      lines.push(`  - ${suit}${it.名称}${part} 星级:${it.星级||''} 稀有:${it.稀有度||''}`)
    }
  }
  return lines.join('\n')
}

export default { preview }
